package com.qst.medical.controller;

import com.qst.medical.mapper.AccountMapper;
import com.qst.medical.model.AccountModel;
import com.qst.medical.util.JwtUtils;
import com.qst.medical.util.Msg;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class LoginController {

    @Autowired
    private AccountMapper accountMapper;

    // 处理JSON格式的登录请求
    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Msg loginJson(@RequestBody(required = false) LoginRequest request) {
        // 检查请求体是否为空
        if (request == null) {
            return Msg.fail()
                    .mess("Missing request body. Please provide JSON body with 'username' and 'password' fields.")
                    .code(10003);
        }

        // 检查用户名和密码是否为空
        if (request.getUsername() == null || request.getUsername().isEmpty() ||
                request.getPassword() == null || request.getPassword().isEmpty()) {
            return Msg.fail()
                    .mess("Username and password are required.")
                    .code(10004);
        }

        return processLogin(request.getUsername(), request.getPassword());
    }

    // 处理表单格式的登录请求
    @PostMapping(value = "/login", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Msg loginForm(@RequestPart(value = "username", required = false) String username,
                         @RequestPart(value = "password", required = false) String password) {
        // 检查用户名和密码是否为空
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            return Msg.fail()
                    .mess("Username and password are required.")
                    .code(10004);
        }

        return processLogin(username, password);
    }

    // 处理application/x-www-form-urlencoded格式的登录请求
    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Msg loginUrlEncoded(@RequestParam(value = "username", required = false) String username,
                               @RequestParam(value = "password", required = false) String password) {
        // 检查用户名和密码是否为空
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            return Msg.fail()
                    .mess("Username and password are required.")
                    .code(10004);
        }

        return processLogin(username, password);
    }


    // 统一处理登录逻辑
    private Msg processLogin(String username, String password) {
        // 获取用户信息
        AccountModel user = accountMapper.selectByUsername(username);

        if (user != null && new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            // 生成JWT令牌
            String token = JwtUtils.getJwtToken(user.getId(), user.getUsername(), null);
            return Msg.success()
                    .data("token", token)
                    .data("userInfo", user)
                    .mess("登录成功");
        }

        return Msg.fail()
                .mess("用户名或密码错误")
                .code(10001);
    }

    // 内部类定义
    @Data
    static class LoginRequest {
        private String username;
        private String password;
    }
}